
import platform
from selenium import webdriver
import pytest
from common.readCofig import *
import time
from selenium.webdriver.chrome.options import Options
from business.Login.login_business import LoginBusiness
from business.Data_Center.my_api_business import DataCenterBusiness
from common.read_yaml import get_yaml_filepath

data = get_yaml_filepath()#读取数据

Firefox = 'firefox'
Chrome = 'chrome'
IE = 'ie'
Grid = 'grid'
FirefoxHeadless = 'firefox-headless'
ChromeHeadless = 'chrome-headless'
@pytest.fixture(scope="session")
def driver1(request):
    global driver
    def end():
        print("全部用例执行完后 teardown quit dirver1")
        time.sleep(5)
        driver.quit()

    # 注册一个清理函数
    request.addfinalizer(end)
    if browerType == Chrome:
        # 本地chrome浏览器
        chrome_options = webdriver.ChromeOptions()

        driver = webdriver.Chrome(options=chrome_options)
        driver.maximize_window()
        _login()
    elif browerType == ChromeHeadless:
        # chrome headless模式
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")#wuj
        chrome_options.add_argument("--window-size=1920x1080")
        chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
        chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
        chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片，提升运行速度

        driver = webdriver.Chrome(options=chrome_options)
        _login()
    elif browerType == Firefox:
        # 本地firefox浏览器
        driver = webdriver.Firefox()
        driver.maximize_window()
        driver.implicitly_wait(timeout)
        _login()

    elif browerType == FirefoxHeadless:
        # firefox headless模式
        firefox_options = webdriver.FirefoxOptions()
        firefox_options.headless = True
        driver = webdriver.Firefox(firefox_options=firefox_options)
        _login()
    # elif browerType == Grid:
    #     # 通过远程节点运行
    #     chrome_capabilities = {
    #         "browserName": "chrome",
    #         "version": "",
    #         "platform": "ANY",
    #         "javascriptEnabled": True,
    #         # "marionette": True,
    #     }
    #
    #     driver = webdriver.Remote(hubIP, desired_capabilities=chrome_capabilities)
    #
    #     driver.set_window_size(1920, 1080)
    #
    # else:
    #     raise NameError("driver驱动类型定义错误！")

    return driver




#def driver1(request):
#     """定义全局driver fixture，给其它地方作参数调用"""
#     if platform.system()=='Windows':
#         print("当前运行的操作系统为windows")
#         chrome_options = Options()
#         chrome_options.add_argument('--window-size=1920,1080')  # 设置当前窗口的宽度，高度
#         # chrome_options.add_argument('--headless')  # 无界面
#         _driver = webdriver.Chrome(options=chrome_options)
#         # _driver.get(url)
#         _driver.get("https://www.oschina.net/home/login")
#         login1=LoginBusiness(_driver)
#         login1.login("18821768014","hbq19941120")
#
#     else:
#         print('当前运行的操作系统为linux')
#         chrome_options = Options()
#         chrome_options.add_argument('--no-sandbox')#解决DevToolsActivePort文件不存在报错问题
#         chrome_options.add_argument('--window-size=1920,1080')  # 设置当前窗口的宽度，高度
#         chrome_options.add_argument('--disable-gpu')#禁用GPU硬件加速，如果软件渲染器没有就位，则GPU进程将不会启动
#         chrome_options.add_argument('--disable-dev-shm-usage')#-禁用-开发-SHM-使用
#         chrome_options.add_argument('--headless')  # 无界面
#         _driver = webdriver.Chrome(options=chrome_options)
#         # _driver.get(data['URL'])
#         _driver.get("https://www.oschina.net/home/login")
#         print('打开了网页')
#
    # def end():
    #     print("全部用例执行完后 teardown quit dirver1")
    #     time.sleep(5)
    #     _driver.quit()
    #
    # # 注册一个清理函数
    # request.addfinalizer(end)
    # # 注册完清理函数后，如果在测试固件里抛出异常,清理函数照常执行
    # return _driver
def _login():
    driver.get(data['URL'])
    driver.implicitly_wait(int(timeout))
    login1 = LoginBusiness(driver)
    login1.login(data['login1']['user_name'], data['login1']['password'])
#
@pytest.fixture
def _driver(driver1):
    driver = DataCenterBusiness(driver1)
    yield driver1,driver  # init driver对象  lg页面对象

# 一、测试用例出现问题时，使用yield与request.addfinalizer（）函数哪个好？
# 答：request.addfinalizer（）函数会更好。当测试用例出现问题时，yield后面的teardown将不会被执行，
# 而addfinalizer的teardown会被执行

# 二、setup出现问题时，使用yield与request.addfinalizer（）函数哪个好？
# 答：request.addfinalizer（）函数会更好。当setup出现问题了，addfinalizer会执行teardown操作
# 总结：一个测试固件没有返回值且确保setup不会出现问题时用yield更容易理解，其他情况使用addfinalizer函数更好

#每个方法执行前都会执行清理其他标签页
@pytest.fixture(autouse=True)
def close():
    yield
    First_handle = driver.current_window_handle
    n = driver.window_handles
    print(n)
    for handle in n:
        if handle != First_handle:
            driver.switch_to.window(handle)
            # 做完一系列操作后关闭school_handle
            driver.close()
            # 切换窗口会第一个窗口
    driver.switch_to.window(First_handle)
    # driver.get(data['URL'])